//
//  JKShareView.swift
//  ZhiHuDaily-Swift
//
//  Created by albert on 2018/3/15.
//  Copyright © 2018年 安永博. All rights reserved.
//

import UIKit
import MessageUI
import JKAlertX

class JKShareView: UIView {
    
    // MARK: - 公共函数
    
    /** 分享url*/
    public class func showWithShareUrl(url: String?, title: String?) {
        
        guard let _ = url else { return }
        
        guard let shareV = Bundle.main.loadNibNamed("JKShareView", owner: nil, options: nil)?.last as? JKShareView else{
            return
        }
        
        shareV.shareUrl = url!
        shareV.shareTitle = title
        shareV.frame = UIScreen.main.bounds
        shareV.cancelTopCons.constant = -38
        shareV.shareContainerBottomCons.constant = -53
        shareV.collectionBtn.isHidden = true
        shareV.titleLabel.text = "分享"
        UIApplication.shared.delegate?.window!?.rootViewController?.view.addSubview(shareV)
    }
    
    /** 详情页 显示分享界面 */
    public class func showWithModel(model: JKNewsDetailModel?) {
        
        if model == nil { return }
        if model!.share_url == nil { return }
        
        guard let shareV = Bundle.main.loadNibNamed("JKShareView", owner: nil, options: nil)?.last as? JKShareView else {
            
            return
        }
        
        shareV.model = model
        shareV.frame = UIScreen.main.bounds
        UIApplication.shared.delegate?.window!?.rootViewController?.view.addSubview(shareV)
    }
    
    // MARK: - 私有属性
    
    @IBOutlet weak var bgView: UIView!
    @IBOutlet weak var shareContainerView: UIView!
    @IBOutlet weak var scrollView: UIScrollView!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var collectionBtn: UIButton!
    @IBOutlet weak var cancelBtn: UIButton!
    @IBOutlet weak var pageControl: UIPageControl!
    @IBOutlet weak var cancelTopCons: NSLayoutConstraint!
    @IBOutlet weak var shareContainerBottomCons: NSLayoutConstraint!
    @IBOutlet weak var shareViewHCons: NSLayoutConstraint!
    
    
    /** 分享的url */
    private var shareUrl: String?
    
    /** 分享的url */
    private var shareTitle: String?
    
    /** 详情模型数据 */
    private var model: JKNewsDetailModel? {
        
        didSet{
            
            self.shareUrl = model?.share_url
            self.shareTitle = model?.title
        }
    }
    
    /** 当前状态栏样式 */
    private var currentStatusBarStyle: UIStatusBarStyle?
    
    
    // MARK: - 初始化
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        initialization()
    }
    
    override func awakeFromNib() {
        super.awakeFromNib()
        
        
        initialization()
    }
    
    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        
//        initialization()
    }
    
    private func initialization() {
        
        NotificationCenter.default.addObserver(self, selector: #selector(updateSkin), name: NSNotification.Name(JKSkinModelDidChangedNotification), object: nil)
        updateSkin()
        
        self.scrollView.delegate = self

        self.bgView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(cancelButtonClick)))

        self.shareContainerView.y = JKScreenH

        self.shareViewHCons.constant = 350 + JKCurrentHomeIndicatorHeight
    }
    
    override func didMoveToSuperview() {
        super.didMoveToSuperview()
        
        if superview == nil { return }
        
        UIView.animate(withDuration: 0.25) {
            
            self.bgView.alpha = 0.5
            self.shareContainerView.y = JKScreenH - self.shareViewHCons.constant
        }
    }
    
    deinit {
        
        NotificationCenter.default.removeObserver(self)
    }
    
    // MARK: - 点击事件
    
    @IBAction func copyUrlClick(_ sender: Any) {
        
        UIPasteboard.general.string = shareUrl
        
        JKProgressHUD.showSuccess(withStatus: "复制成功！")
    }
    
    @IBAction func shareToWXSession(_ sender: Any) {
        
        shareWithType(type: .wechatSession)
    }
    
    @IBAction func shareToWXTimeline(_ sender: Any) {
        
        shareWithType(type: .wechatTimeline)
    }
    
    @IBAction func shareToWeibo(_ sender: Any) {
        
        shareWithType(type: .sina)
    }
    
    @IBAction func WXCollection(_ sender: Any) {
        
        shareWithType(type: .wechatFavorite)
    }
    
    /** shareWithType */
    private func shareWithType(type: JKShareType) {
        
        cancelButtonClick()
        
        if (self.model == nil) {
            
            JKShareManager.share(url: self.shareUrl, text: self.shareTitle, description: self.shareTitle, imageUrl: nil, shareType: type)
            
            return
        }
        
        JKShareManager.share(url: self.shareUrl, text: self.shareTitle, description: self.shareTitle, imageUrl: self.model!.images?[0], shareType: type)
    }
    
    @IBAction func shareToMessage(_ sender: Any) {
        
        // 判断能否发送短信
        if !MFMessageComposeViewController.canSendText() {
            
            let _ = JKAlertView(title: nil, message: "当前无法发送短信！", style: JKAlertStylePlain).addAction(JKAlertAction(title: "确定", style: JKAlertActionStyleDefault, handler: { (action) in
                
            }))?.show()
            
            return
        }
        
        // 要想设置短信内容，我们使用MessageUI
        // 创建
        let msgVc = MFMessageComposeViewController()
        
        // 设置电话
        //msgVc.recipients = @[@"10086",@"10010"]
        
        // 设置内容
        msgVc.body = "【" + (shareTitle ?? "") + "】（分享自ZhiHuDaily-ayb）" + (shareUrl ?? "")
        
        // 设置代理 点击取消或发送之后返回页面
        // 使用这个代理 messageComposeDelegate
        msgVc.messageComposeDelegate = self
        
        // 显示短信界面
        UIApplication.shared.delegate?.window!?.rootViewController?.present(msgVc, animated: true, completion: {
            
            self.cancelButtonClick()
            
            self.currentStatusBarStyle = UIApplication.shared.statusBarStyle
            UIApplication.shared.setStatusBarStyle(UIStatusBarStyle.default, animated: true)
        })
    }
    
    @IBAction func collectionClick(_ sender: Any) {
        
        cancelButtonClick()
        
        if self.model == nil {
            return
        }
        
        if JKSQLiteManager.queryIsCollectedWithStoryID(storyID: self.model!.id) {
            
            JKProgressHUD.showInfo(withStatus: "您已收藏该文章！")
            
            return
        }
        
        if JKSQLiteManager.updateCollectedStatusWithStoryID(storyID: self.model!.id, collected: true) {
            
            JKProgressHUD.showSuccess(withStatus: "收藏成功！")
            
            return
        }
        
        JKProgressHUD.showError(withStatus: "收藏失败！")
    }
    
    @IBAction func cancelButtonClick() {
        
        UIView.animate(withDuration: 0.25, animations: {
            
            self.bgView.alpha = 0
            self.shareContainerView.y = JKScreenH
            
        }) { (_) in
            
            self.removeFromSuperview()
        }

    }
}

extension JKShareView: UIScrollViewDelegate {
    
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        
        self.pageControl.currentPage = (scrollView.contentOffset.x >= JKScreenW) ? 1 : 0
    }
}

extension JKShareView: MFMessageComposeViewControllerDelegate {
    
    func messageComposeViewController(_ controller: MFMessageComposeViewController, didFinishWith result: MessageComposeResult) {
        
        // MessageComposeResultCancelled,
        // MessageComposeResultSent,
        // MessageComposeResultFailed
        
        if (result == MessageComposeResult.cancelled || result == MessageComposeResult.sent) {
            
            controller.dismiss(animated: true, completion: nil)
        }
        
        UIApplication.shared.setStatusBarStyle(currentStatusBarStyle!, animated: true)
    }
}

extension JKShareView: JKUpdateSkinProtocol {
    
    func updateSkin() {
        
        if UserDefaults.standard.string(forKey: JKCurrentSkinModelKey) == JKNightSkinModelValue { // 夜间模式
            
            self.shareContainerView.backgroundColor = JKNightSkinBgColor
            self.titleLabel.textColor = JKColor(218, 218, 218)
            
            self.collectionBtn.setBackgroundImage(UIImage(named: "bg_normal_night"), for: UIControlState.normal)
            self.collectionBtn.setBackgroundImage(UIImage(named: "bg_highlighted_night"), for: UIControlState.highlighted)
            
            self.cancelBtn.setBackgroundImage(UIImage(named: "bg_normal_night"), for: UIControlState.normal)
            self.cancelBtn.setBackgroundImage(UIImage(named: "bg_highlighted_night"), for: UIControlState.highlighted)
            
            self.pageControl.pageIndicatorTintColor = JKColor(88, 88, 88)
            self.pageControl.currentPageIndicatorTintColor = JKColor(218, 218, 218)
            
        }else{ // 日间模式
            
            self.shareContainerView.backgroundColor = JKColor(237, 237, 237)
            self.titleLabel.textColor = UIColor.black
            
            self.collectionBtn.setBackgroundImage(UIImage(named: "bg_normal_day"), for: UIControlState.normal)
            self.collectionBtn.setBackgroundImage(UIImage(named: "bg_highlighted_day"), for: UIControlState.highlighted)
            
            self.cancelBtn.setBackgroundImage(UIImage(named: "bg_normal_day"), for: UIControlState.normal)
            self.cancelBtn.setBackgroundImage(UIImage(named: "bg_highlighted_day"), for: UIControlState.highlighted)
            
            self.pageControl.currentPageIndicatorTintColor = JKColor(88, 88, 88)
            self.pageControl.pageIndicatorTintColor = JKColor(218, 218, 218)
        }
    }
}

